const http = require('http');
const https = require('https');
const express = require('express')
const app = express()
const port = 3000

let SQLHelper = require('./SQLHelper')

// SQLHelper('select * from member').then(res =>{
//     console.log('I am mysql',res);
// })

app.use(express.static('juzhao'))
app.get('/wx/login', (req, res) => {
    console.log(req.headers)
    let code = req.query.code
    let appid = 'wx9a6af80e3356e952'
    let secret = '08da3b5e03ab70772a6b2074b4eaebf0'
    https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
      ret.on('data', (ret) => {
        ret = JSON.parse(ret.toString())
        let openid = ret.openid
        if(!openid){
          res.send({errorMsg: ret.errMsg ||'获取openid错误'})
        }else{
          //查询用户是否已经注册
          let queryMember = `select *from member where openid = '${openid}'`
          SQLHelper(queryMember).then(membersRet =>{
            if(membersRet.length){//用户存在
              res.send(membersRet[0])
            }else{//用户不存在,使用openid注册用户
              SQLHelper(`INSERT INTO member (openid) VALUES('${openid}')`).then(newMember =>{
                //注册成功返回新用户信息
                SQLHelper(queryMember).then(newMember =>{
                  res.send(newMember)
                })
              })

            }
          })
        }
      });

        }).on('error', (e) => {
            console.error(e);
            res.status(404)

            });

})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})
